package com.siashan.toolkit.captcha.google;

import com.siashan.toolkit.captcha.cache.CaptchaCacheTemplate;
import com.siashan.toolkit.captcha.core.CaptchaCkResult;
import com.siashan.toolkit.captcha.core.CaptchaData;
import com.siashan.toolkit.captcha.core.CaptchaInfo;
import lombok.Getter;
import lombok.Setter;

/**
 * Easy图形验证码构造器
 *
 * @author siashan
 * @since v1.0.5
 **/
@Setter
@Getter
public class GoogleCaptchaTemplate {

    private CaptchaCacheTemplate captchaCacheTemplate;

    public GoogleCaptchaTemplate(CaptchaCacheTemplate captchaCacheTemplate) {
        this.captchaCacheTemplate = captchaCacheTemplate;
    }

    /**
     * 渲染图形验证码
     *
     * @return CaptchaInfo
     */
    public CaptchaInfo render() {
        GoogleCaptcha googleCaptcha = GoogleCaptchaBuilder.build();
        CaptchaData render = GoogleCaptchaUtil.render(googleCaptcha.getKaptcha(), googleCaptcha.getCaptchaType());
        CaptchaInfo captchaInfo = render.getCaptchaInfo();
        captchaCacheTemplate.put(captchaInfo.getUuid(), render.getCaptchaText(), 3);
        return captchaInfo;
    }

    /**
     * 渲染图形验证码
     *
     * @param captchaType 验证码类型
     * @return CaptchaInfo
     */
    public CaptchaInfo render(GoogleCaptchaType captchaType) {
        GoogleCaptcha googleCaptcha = GoogleCaptchaBuilder.build(captchaType);
        CaptchaData render = GoogleCaptchaUtil.render(googleCaptcha.getKaptcha(), googleCaptcha.getCaptchaType());
        CaptchaInfo captchaInfo = render.getCaptchaInfo();
        captchaCacheTemplate.put(captchaInfo.getUuid(), render.getCaptchaText());
        return captchaInfo;
    }

    /**
     * 校验图形验证码
     *
     * @param key 验证码类型
     * @return CaptchaCkResult
     */
    public CaptchaCkResult validate(String key, String value) {
        String sv = captchaCacheTemplate.get(key);
        captchaCacheTemplate.release(key);
        if (null == sv || "".equals(sv.trim())) {
            return CaptchaCkResult.empty();
        }
        if (sv.equalsIgnoreCase(value)) {
            return CaptchaCkResult.success();
        } else {
            return CaptchaCkResult.fail();
        }
    }
}
